package com.qf.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.handler.Handler;

/**
 * 演示如何编写拦截器
 * 负责拦截到请求后的具体处理逻辑编写
 * pre handler调用 之前做的事情
 * post handler调用 之后做的事情
 */
@Component // 这个注解也会让 springboot启动时帮我们创建这个类的对象
public class TimeInterception implements HandlerInterceptor {

    /**
     * pre方法的返回值,如果为true,那么本次请求会继续向后发送给controller中的方法(handler)
     * 如果返回false,那么请求就到此为止
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(request.getRequestURI()+"=================>");

        // 如果没有传name,那么不让请求向后发送
        if (request.getParameter("name") == null) {
            throw new RuntimeException("name没有参数");
//            return false;
        }

        long start = System.currentTimeMillis();
        request.setAttribute("start",start);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long start = (long) request.getAttribute("start");
        long end = System.currentTimeMillis();
        String requestURI = request.getRequestURI();
        System.out.println(requestURI+":time cost="+(end - start));
        System.out.println(request.getRequestURI()+"<=================");

    }
}
